package cn.growthgate.fgo.web;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;

import cn.growthgate.fgo.common.Constants;
import cn.growthgate.fgo.entity.Class;
import cn.growthgate.fgo.entity.ClassIntermediary;
import cn.growthgate.fgo.entity.Image;
import cn.growthgate.fgo.service.IClassIntermediaryService;
import cn.growthgate.fgo.service.IClassService;
import cn.growthgate.fgo.service.IImageService;
import cn.growthgate.fgo.util.StringUtils;
import cn.growthgate.fgo.web.result.JsonResult;
import cn.growthgate.fgo.web.result.TableResult;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author GrowthGate
 * @since 2019-01-20
 */
@Controller
@RequestMapping("/class")
public class ClassController {

	@Autowired
	private IClassService classService;

	@Autowired
	private IImageService imageService;

	@Autowired
	private IClassIntermediaryService classIntermediaryService;

	@RequestMapping("/list")
	@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
	public String list() {
		return "class/list";
	}

	@ResponseBody
	@RequestMapping("/tableData")
	@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
	public TableResult<Class> tableData(Class entity, Integer current, Integer size, String orderByField,
			Boolean isAsc) {
		Wrapper<Class> wrapper = new EntityWrapper<>();

		Page<Class> page = classService.selectPage(current, size, orderByField, isAsc, wrapper);
		return new TableResult<Class>(page);
	}

	@RequestMapping("/form")
	@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
	public ModelAndView form(Long id) {
		Class entity = classService.selectById(id);

		return new ModelAndView("class/form").addObject("entity", entity);
	}

	@ResponseBody
	@RequestMapping("/save")
	@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
	public JsonResult save(@Validated Class entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return JsonResult.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
		}
		if (entity.getId() != null) {
			// 编辑
			Class oEntity = classService.selectById(entity.getId());
			// 更改图片
			changeImage(oEntity.getGoldenIcon(), entity.getGoldenIcon());
			changeImage(oEntity.getSilverIcon(), entity.getSilverIcon());
			changeImage(oEntity.getBronzeIcon(), entity.getBronzeIcon());
			changeImage(oEntity.getBlackIcon(), entity.getBlackIcon());
			changeImage(oEntity.getGoldenImage(), entity.getGoldenImage());
			changeImage(oEntity.getSilverImage(), entity.getSilverImage());
			changeImage(oEntity.getBronzelmage(), entity.getBronzelmage());
			changeImage(oEntity.getBlackImage(), entity.getBlackImage());
		}
		classService.insertOrUpdate(entity);
		updateImage(entity, entity.getGoldenIcon());
		updateImage(entity, entity.getSilverIcon());
		updateImage(entity, entity.getBronzeIcon());
		updateImage(entity, entity.getBlackIcon());
		updateImage(entity, entity.getGoldenImage());
		updateImage(entity, entity.getSilverImage());
		updateImage(entity, entity.getBronzelmage());
		updateImage(entity, entity.getBlackImage());
		return JsonResult.ok();
	}

	private void changeImage(String oUuid, String uuid) {
		if (oUuid != null && !oUuid.equals(uuid)) {
			imageService.deleteByUUID(oUuid);
		}
	}

	private void updateImage(Class entity, String uuid) {
		if (StringUtils.isNotBlank(uuid)) {
			Image image = imageService.getByUUID(uuid);
			image.setEntityId(entity.getId());
			image.setEntityName(entity.getClass().getSimpleName());
			imageService.updateById(image);
		}
	}

	@ResponseBody
	@RequestMapping("/delete")
	@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
	public JsonResult delete(Long[] ids) {
		if (classService.deleteBatchIds(Arrays.asList(ids))) {
			imageService.deleteByEntity(Class.class.getSimpleName(), ids);
			return JsonResult.ok("删除成功");
		} else {
			return JsonResult.fail("删除失败");
		}
	}

	@RequestMapping("/show")
	public ModelAndView show() {
		List<Class> classes = classService.selectAll();
		// 获取职介相性数据
		List<ClassIntermediary> classIntermediaries = classIntermediaryService.selectAll();
		Map<Long, Map<Long, BigDecimal>> classIntermediaryMap = classes.stream()
				.collect(Collectors.toMap(Class::getId, entity -> new HashMap<>()));
		for (ClassIntermediary classIntermediary : classIntermediaries) {
			Map<Long, BigDecimal> map = classIntermediaryMap.get(classIntermediary.getAttackerId());
			map.put(classIntermediary.getDefenderId(), classIntermediary.getDamage());
		}

		return new ModelAndView("class/show").addObject("classes", classes).addObject("classIntermediaryMap",
				classIntermediaryMap);
	}

}
